package com.itheima.Service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Service.AddressBookService;
import com.itheima.Service.OrderService;
import com.itheima.bean.*;
import com.itheima.common.R;
import com.itheima.dao.*;
import com.itheima.dto.DishDto;
import com.itheima.dto.OrdersDto;
import com.itheima.util.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private DishDao dishDao;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private OrdersDetailDao ordersDetailDao;
    /**
     * 订单分页查询+条件查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public IPage<OrdersDto> findPage(int page, int pageSize, Long number, Date beginTime, Date endTime) {
        //查询出orders的分页数据
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> olqw = new LambdaQueryWrapper<>();
        olqw.eq(number != null, Orders::getId, number);
        olqw.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);
        olqw.orderByDesc(Orders::getOrderTime);
        ordersDao.selectPage(ordersPage, olqw);
        /**
         *    查询地址
         *    将orderPage对象中的orders集合遍历取出，存入orderDto对象中并封装进去地址
         *    将orderPage对象复制给DtoPage对象
         */
        List<OrdersDto> collect = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
            String address = (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                    (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                    (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                    (addressBook.getDetail() != null ? addressBook.getDetail() : "");
            ordersDto.setAddress(address);
            return ordersDto;
        }).collect(Collectors.toList());

        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        ordersDtoPage.setRecords(collect);

        return ordersDtoPage;
    }

    /**
     * 订单提交
     * 1获取用户id,查询当前用户的购物车数据
     * 2 根据id 查询用户对象
     * 3 根据地址ID 查询地址信息
     * 4 组装订单明细数据，批量保存订单明细
     * 5 组装订单数据，批量保存订单数据
     * 6 删除当前用户购物车数据
     *
     * @param orders
     * @return
     */
    @Override
    public int submit(Orders orders) {
        try {
            Long userId= BaseContext.getCurrentId();
            User user = userDao.selectById(userId);
            LambdaQueryWrapper<AddressBook> ab = new LambdaQueryWrapper<>();
            ab.eq(AddressBook::getUserId,userId);
            AddressBook addressBook = addressBookService.getOne(ab);
            //购物车信息集合
            LambdaQueryWrapper<ShoppingCart> slqw = new LambdaQueryWrapper<>();
            slqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
            List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(slqw);

            double amount=0.0;
            //总金额
            for (ShoppingCart shoppingCart : shoppingCarts) {
                System.out.println("shoppingCart = " + shoppingCart);
                int number = shoppingCart.getNumber();
                if (shoppingCart.getDishId()!=null){
                    Long dishId = shoppingCart.getDishId();
                    Dish byId = dishDao.selectById(dishId);
                    double price = byId.getPrice().doubleValue();
                    amount+=number*price;
                }else if (shoppingCart.getSetmealId()!=null){
                    Long setmealId= shoppingCart.getSetmealId();
                    Setmeal byId = setmealDao.selectById(setmealId);
                    System.out.println("byId = " + byId);
                    double price = byId.getPrice().doubleValue();
                    amount+=price*number;
                }
            }

            orders.setNumber(UUID.randomUUID().toString().replace("-",""));
            orders.setStatus(1);
            orders.setUserId(BaseContext.getCurrentId());
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setUserName(user.getName());//java.lang.NullPointerException: null
            orders.setPhone(addressBook.getPhone());
            orders.setConsignee(addressBook.getConsignee());
            String address=(addressBook.getProvinceName()!=null?addressBook.getProvinceName():"")+
                    (addressBook.getCityName()!=null?addressBook.getCityName():"")+
                    (addressBook.getDistrictName()!=null?addressBook.getDistrictName():"")+
                    (addressBook.getDetail()!=null?addressBook.getDetail():"");
            orders.setAddress(address);
            orders.setAmount(new BigDecimal(amount));
            ordersDao.insert(orders);
            for (ShoppingCart shoppingCart : shoppingCarts) {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(shoppingCart,orderDetail,"id");
                orderDetail.setOrderId(orders.getId());
                int insert = ordersDetailDao.insert(orderDetail);
            }
            //清空购物车
            LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
            sclqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
            int delete = shoppingCartDao.delete(sclqw);
            return 1;
        } catch (BeansException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
